package ytmc;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;


/**
 *
 * @author Kicok
 */
public class TimePeriod
{
    private int hours;
    private int minutes;
    private int seconds;
    private int miliseconds;


    public TimePeriod( int seconds )
    {
        if( seconds < 0 )
        {
            seconds = 0;
        }
        
        this.hours = ( seconds / 3600 ) % 24;
        this.minutes = ( seconds / 60 ) % 60;
        this.seconds = seconds% 60;
        this.miliseconds = 0;
    }

    public TimePeriod( long miliseconds )
    {
        if( miliseconds < 0 )
        {
            miliseconds = 0;
        }

        this.hours = (int)( miliseconds / 3600000 ) % 24;
        this.minutes = (int)( miliseconds / 60000 ) % 60;
        this.seconds = (int)( miliseconds / 1000 ) % 60;
        this.miliseconds = (int)( miliseconds % 1000 );
    }

    public TimePeriod( String time )
    {
        Pattern timePattern = Pattern.compile( "^([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\\.([0-9]{0,3}))?" );
        Matcher m = timePattern.matcher( time );

        if( m.matches() )
        {
            this.hours = Integer.parseInt( m.group( 1 ) );
            this.minutes = Integer.parseInt( m.group( 2 ) );
            this.seconds = Integer.parseInt( m.group( 3 ) );
            String mili = StringUtils.rightPad( m.group( 4 ), 3, '0' );
            this.miliseconds = Integer.parseInt( mili );
        }
        else
        {
            System.out.println( "Nie udało się dopasować czasu do wyrażenia: " + time );
        }
    }


    public int getHours()
    {
        return hours;
    }

    public int getMinutes()
    {
        return minutes;
    }

    public int getSeconds()
    {
        return seconds;
    }

    public int getMiliseconds()
    {
        return miliseconds;
    }


    @Override
    public String toString()
    {
        return String.format( "%02d:%02d:%02d", hours, minutes, seconds );
    }

    public double toSeconds()
    {
        double dSeconds = hours * 3600;
        dSeconds += minutes * 60;
        dSeconds += seconds;
        dSeconds += miliseconds / 1000.0;

        return dSeconds;
    }
}